package com.flightgame.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class UserDao {
	@Autowired
	private SessionFactory sessionFactory;
	
	@Transactional
	public void addUser(User user){
		try{
			sessionFactory.getCurrentSession().persist(user);
			}
		catch(Exception sq){
			sq.printStackTrace();
		}
	}
	
    @SuppressWarnings("unchecked")
	public List<User> getUsers(){
		return sessionFactory.getCurrentSession().createQuery("from User").list();
	}
    
    public boolean isUserExist(String username){
    	boolean result = sessionFactory.getCurrentSession().createQuery("from User where username =:username").setParameter("username",username).uniqueResult() != null ? true : false;
    	return result;

    }
    
    public User getUserWithId(int userId){
    	return (User)sessionFactory.getCurrentSession().createQuery("from User where id =:id").setParameter("id",userId).uniqueResult();
    }
    
    public User getUser(String username){
    	return (User) sessionFactory.getCurrentSession().createQuery("from User where username =:username").setParameter("username",username).uniqueResult();
    }
    
    public void transferCredit(String userFrom,String userTo,int quantity){
    	decreaseIncreaseUserCredit(userFrom,(-1) * quantity);
		decreaseIncreaseUserCredit(userTo,quantity);
    }
    
    @Transactional
    public int decreaseIncreaseUserCredit(String username,int quantity){
    	User user = getUser(username);
    	int credits = user.getCredits() + quantity;
    	
    	user.setCredits(credits);
    	sessionFactory.getCurrentSession().update(user);
    	
    	return credits;
    }
    
}